package org.crystalrange.files.web;

import org.crystalrange.BaseController;
import org.crystalrange.Message;
import org.crystalrange.files.model.File;
import org.crystalrange.files.model.FileType;
import org.crystalrange.files.service.FileService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Window;

public class FileController extends BaseController {

	private File file;
	private FileService fileService;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public FileService getFileService() {
		return fileService;
	}

	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}

	public void onClick$toolbarbuttonFileSave(Event event) throws Exception {
		this.fileSave();
	}

	public void onClick$menuitemFileSave(Event event) throws Exception {
		this.fileSave();
	}

	private void fileSave() throws Exception {
		if (this.file.getName() != null && this.file.getFileType() != null) {
			this.fileService.save(this.file);
			this.sessionScope.put("CRYSTALRANGE_MESSAGE", new Message("Saved successfully!"));
			Clients.evalJavaScript("window.history.back();");
		} else {
			this.message.setText("You must enter 'File Name' and select 'File Type'.");
            this.message.setIcon("/img/exclamation.png");
            this.binder.loadAll();
		}
	}

	@Override
	public void doAfterCompose(Component component) throws Exception {
		super.doAfterCompose(component);

		if (this.execution.getParameter("Id") != null) {
			this.file = this.fileService.find(Long.parseLong(this.execution
					.getParameter("Id")));
			this.labelTitle.setValue("Edit File");
		} else {
			this.file = this.fileService.create(SecurityContextHolder
					.getContext().getAuthentication().getName());
			this.labelTitle.setValue("Create File");
		}

		component.setAttribute("controller", this);
	}

	public void onOpen$bandboxFileType(Event event) throws Exception {
		Window window = (Window) this.execution.createComponents(
				"~./zul/html/fileTypeSelect.zul", null, null);
		window.setParent(self);
		window.doModal();

		if (this.execution.getAttribute("result") == "ok") {
			FileType selectedFileType = (FileType) this.execution
					.getAttribute("selectedFileType");
			this.file.setFileType(selectedFileType);
		}

		this.binder.loadAll();
	}
}
